#include "netgame.h"
#include<QDebug>

NetGame::NetGame(MainWindow* _mainWindow,bool isServer):Board(_mainWindow)
{
    isNetGame=true;
    server = NULL;
    socket = NULL;
    if (isServer) {
        server = new QTcpServer(this);
        server->listen(QHostAddress::Any, 9999);
        connect(server, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
    } else {
        socket = new QTcpSocket(this);
        socket->connectToHost(QHostAddress("127.0.0.1"), 9999);
        connect(socket, SIGNAL(readyRead()), this, SLOT(slotRecv()));
    }
}

void NetGame::slotNewConnection()
{
    if (socket)
        return;
    socket = server->nextPendingConnection();
    connect(socket, SIGNAL(readyRead()), this, SLOT(slotRecv()));
    qDebug() << "connect";
}

void NetGame::slotRecv()
{
    QByteArray ba = socket->readAll();
    Board::clickHandler(ba[0], ba[1], ba[2]);
}

void NetGame::clickHandler(int clickId, int row, int col)
{
    Board::clickHandler(clickId, row, col);
    //发送给对方
    QByteArray ba;
    ba.append(clickId);
    ba.append(row);
    ba.append(col);
    socket->write(ba);
}
